package com.hengjun.baccarat;

import java.util.List;

import com.hengjun.baccarat.net.Server;
import com.hengjun.baccarat.net.UpdateManager;
import com.hengjun.baccarat.net.UrlConn;
import com.hengjun.baccarat.pojo.GlobalService;
import com.hengjun.baccarat.pojo.ViewDataObject;
import com.hengjun.baccarat.utils.RecordCore;
import com.hengjun.baccarat.utils.ThreadManager;
import com.hengjun.baccarat.utils.XListView;
import com.hengjun.baccarat.utils.XListView.IXListViewListener;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class OrderList extends Activity implements IXListViewListener {
	private Handler mHandler;
	private XListView mListView;
	private listViewAdapter adapter;
	private List<RecordCore> rcList = GlobalService.list;
	private ProgressDialog dialog;
	public static int point;
	private UpdateManager update = new UpdateManager(this);
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activty_list);

		ThreadManager.handler = new testHander();
		initView();
	}

	private void initView() {
		mListView = (XListView) findViewById(R.id.xListView);
		mListView.setPullLoadEnable(true);
		adapter = new listViewAdapter(R.layout.orderlist_item);
		mListView.setAdapter(adapter);
		mListView.setXListViewListener(this);
		mListView.setOnItemClickListener(new ClickListener());
		mHandler = new Handler();
	}

	public void toLogin(View v) {
		Server.SERVER.close();
		Intent intent = new Intent(OrderList.this, Login.class);
		startActivity(intent);
		OrderList.this.finish();
	}

	private class listViewAdapter extends BaseAdapter {
		private LayoutInflater inflater;
		private int resource;
		public listViewAdapter(int resource) {
			this.resource = resource;
			inflater = getLayoutInflater();
		}

		public int getCount() {
			return GlobalService.list.size();
		}

		public Object getItem(int pos) {
			return GlobalService.list.get(pos);
		}

		public long getItemId(int pos) {
			return pos;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View view = null;
			if(convertView != null){
				view = convertView;
			}else{
				view = inflater.inflate(resource, parent, false);  
			}
			
			TextView listData = (TextView) view.findViewById(R.id.listData);
			
			rcList = rcList == null ? GlobalService.list : rcList;
			String color = "";
			String color2 = "";
			if (rcList.get(position).getRealyCaptial() < 0) {
				color = "<font color=\"#FF0000\">";
			} else {
				color = "<font color=\"#000000\">";
			}
			if (rcList.get(position).getWinorlose() < 0) {
				color2 = "<font color=\"#FF0000\">";
			} else {
				color2 = "<font color=\"#000000\">";
			}
			if (position < rcList.size() && rcList.size() > 0) {
				String listResult = "<font color=\"#000000\">地點:"
						+ rcList.get(position).getGambleaddr()
						+ "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;贵宾厅:"
						+ rcList.get(position).getVipparty()
						+ "<br/>\n單編號:"
						+ rcList.get(position).getRecordsn()
						+ "<br/>\n本金:</font>"
						+ color
						+ GlobalService.getDoubleString(rcList.get(position)
								.getRealyCaptial())
						+ "</font>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<font color=\"#000000\">加彩總額:"
						+ GlobalService.getDoubleString(rcList.get(position)
								.getAddMoney())
						+ "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;上下數:</font>"
						+ color2
						+ GlobalService.getDoubleString(rcList.get(position)
								.getWinorlose()) + "</font>";

				listData.setText(Html.fromHtml(listResult));
				listData.setTextSize(18f);
				listData.setGravity(Gravity.LEFT);
				listData.setHeight(200);
			}
			return view;
		}
	}
	private Dialog errorDialog = null;
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			if (msg.what == 0) {
				try {
					dialog.dismiss();
				} catch (Exception e) {
					e.printStackTrace();
				}
				errorDialog = new Dialog(OrderList.this, R.style.MyDialogStyle);
				errorDialog.setContentView(R.layout.erro_dialog);
				TextView message = (TextView) errorDialog
						.findViewById(R.id.textView1);
				message.setText("網絡連接故障,獲取列表失敗!");
				Button exit = (Button) errorDialog.findViewById(R.id.button1);
				exit.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						errorDialog.dismiss();
						Intent intent = new Intent(OrderList.this, Login.class);
						OrderList.this.startActivity(intent);
						OrderList.this.finish();
					}
				});
				errorDialog.show();
			}

			if (msg.what == 1) {
				try {
					dialog = Login.createProgressDialog(OrderList.this,
							"正在獲取數據");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (msg.what == 2) {
				try {
					dialog.dismiss();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (msg.what == 3) {
				if (rcList.size() == 0) {
					Toast.makeText(OrderList.this, "當前沒有單號可選!",
							Toast.LENGTH_SHORT).show();
					mListView.setAdapter(null);
				}
			}
		}
	};

	private class ClickListener implements OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			point = arg2 - 1;
			DownLoad th = new DownLoad(rcList.get(arg2 - 1));
			th.start();
		}
	}

	private class DownLoad extends Thread {
		private RecordCore recordCore;

		public DownLoad(RecordCore recordCore) {
			this.recordCore = recordCore;
		}

		public void run() {
			try {
				handler.obtainMessage(1).sendToTarget();
				ViewDataObject.resetViewData();
				Intent _intent = new Intent(OrderList.this,
						Activity_Control.class);
				String[] str = new String[] {
						recordCore.getRecordsn(),
						recordCore.getRecordindex() + "",
						GlobalService.getDoubleString(recordCore.getCapital()),
						GlobalService.getDoubleString(recordCore
								.getRealyCaptial()),
						GlobalService.getDoubleString(recordCore.getAddMoney()) };
				UrlConn.ListQuery(str[1] + "");
				_intent.putExtra("list", str);
				OrderList.this.startActivity(_intent);
				handler.obtainMessage(2).sendToTarget();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				handler.obtainMessage(2).sendToTarget();
				e.printStackTrace();
				handler.obtainMessage(0).sendToTarget();
			}
		}
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		onRefresh();
	}

	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		update.closeUpdate();
		if (serverClose != null) {
			serverClose.dismiss();
		}
		if (errorDialog != null) {
			errorDialog.dismiss();
		}
		if (userError != null) {
			userError.dismiss();
		}
		if (netError != null) {
			netError.dismiss();
		}
	}

	@Override
	public void onRefresh() {
		new Refresh().start();
	}

	private void onLoad() {
		mListView.stopRefresh();
		mListView.setRefreshTime("刚刚");
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			try {
				// SocketConnection.socket.close();
				// SocketConnection.socket=null;
				Server.SERVER.close();
				Intent _intent = new Intent(OrderList.this, Login.class);
				OrderList.this.startActivity(_intent);
				OrderList.this.finish();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return true;
		}
		return false;
	}

	private class Refresh extends Thread {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			try {
				GlobalService.list = UrlConn.RecordConn();
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						rcList.clear();
						rcList = GlobalService.list;
						adapter = new listViewAdapter(R.layout.orderlist_item);
						mListView.setAdapter(adapter);
						onLoad();
						handler.obtainMessage(3).sendToTarget();
					}
				});
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				handler.obtainMessage(0).sendToTarget();
			}
		}
	}
	private Dialog userError = null;
	private Dialog serverClose = null;
	private Dialog netError = null;
	@SuppressLint("HandlerLeak")
	private class testHander extends Handler {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			if (msg.what == 0) {
				userError = new Dialog(OrderList.this, R.style.MyDialogStyle);
				userError.setContentView(R.layout.erro_dialog);
				ImageView image = (ImageView) userError
						.findViewById(R.id.imageView1);
				image.setImageResource(R.drawable.confirm_dialog_failweb);
				TextView message = (TextView) userError
						.findViewById(R.id.textView1);
				message.setText("退出提示,賬戶異地登陸!");
				Button exit = (Button) userError.findViewById(R.id.button1);
				exit.setText("退出");
				exit.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						userError.dismiss();
						Intent _intent = new Intent(OrderList.this, Login.class);
						OrderList.this.startActivity(_intent);
						OrderList.this.finish();
					}
				});
				userError.show();
			}
			if (msg.what == -1) {
				serverClose = new Dialog(OrderList.this, R.style.MyDialogStyle);
				serverClose.setContentView(R.layout.erro_dialog);
				TextView message = (TextView) serverClose
						.findViewById(R.id.textView1);
				message.setText("連接失敗,服務器已關閉!");
				Button exit = (Button) serverClose.findViewById(R.id.button1);
				exit.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						serverClose.dismiss();
						Intent _intent = new Intent(OrderList.this, Login.class);
						OrderList.this.startActivity(_intent);
						OrderList.this.finish();
					}
				});
				serverClose.show();
			}
			if (msg.what == 500) {
				netError = new Dialog(OrderList.this, R.style.MyDialogStyle);
				netError.setContentView(R.layout.erro_dialog);
				TextView message = (TextView) netError
						.findViewById(R.id.textView1);
				message.setText("網絡連接故障!");
				Button exit = (Button) netError.findViewById(R.id.button1);
				exit.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						netError.dismiss();
						Intent _intent = new Intent(OrderList.this, Login.class);
						OrderList.this.startActivity(_intent);
						OrderList.this.finish();
					}
				});
				netError.show();
			}
			// 更新
			if (msg.what == 1001) {
				update.showNoticeDialog();
			}
		}
	}

}
